package com.easy.work.function.resume;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.base.syslib.Logs;
import com.base.syslib.impl.OnSelectCityImpl;
import com.base.syslib.impl.OneChoiceImpl;
import com.base.syslib.util.FileUtils;
import com.base.syslib.util.MessageTools;
import com.base.syslib.util.TextUtil;
import com.base.syslib.view.RoundImageView;
import com.easy.work.R;
import com.easy.work.app.AppSession;
import com.easy.work.app.BaseActivity;
import com.easy.work.app.CommonValue;
import com.easy.work.function.mall.bean.JobCommonBean;
import com.easy.work.function.me.fragment.WorkExperienceFragment;
import com.easy.work.http.BaseResponse;
import com.easy.work.http.HttpClient;
import com.easy.work.http.request.CheckResumeRequest;
import com.easy.work.http.request.EducationRequest;
import com.easy.work.http.request.GetResumeInfoRequest;
import com.easy.work.http.request.SaveOrUpdateResumeRequest;
import com.easy.work.http.response.CheckResumeResponse;
import com.easy.work.http.response.ResumeInfoResponse;
import com.easy.work.oss.UICallback;
import com.easy.work.utils.ImageUtils;
import com.easy.work.utils.StringUtil;
import com.easy.work.utils.UserOssUtils;
import com.easy.work.view.dialog.CityDialog;
import com.easy.work.view.dialog.DialogTools;
import com.squareup.picasso.MemoryPolicy;
import com.squareup.picasso.NetworkPolicy;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by admin on 2017/12/24.
 * 我的简历
 */
public class MyResumeAct extends BaseActivity {

    @BindView(R.id.ly_img)
    LinearLayout lyImg;
    @BindView(R.id.et_name)
    EditText etName;
    @BindView(R.id.ly_name)
    LinearLayout lyName;
    @BindView(R.id.tv_sex)
    TextView tvSex;
    @BindView(R.id.ly_sex)
    LinearLayout lySex;
    @BindView(R.id.tv_edu)
    TextView tvEdu;
    @BindView(R.id.ly_edu)
    LinearLayout lyEdu;
    @BindView(R.id.et_work_age)
    TextView etWorkAge;
    @BindView(R.id.tv_national)
    TextView tvNational;
    @BindView(R.id.ly_national)
    LinearLayout lyNational;
    @BindView(R.id.tv_marital)
    TextView tvMarital;
    @BindView(R.id.ly_marital)
    LinearLayout lyMarital;
    @BindView(R.id.tv_censusRegister)
    TextView tvCensusRegister;
    @BindView(R.id.ly_censusRegister)
    LinearLayout lyCensusRegister;
    @BindView(R.id.et_residentialAddress)
    EditText etResidentialAddress;
    @BindView(R.id.et_idcard)
    EditText etIdcard;
    @BindView(R.id.img_person)
    RoundImageView imgPerson;
    /**
     * 保存的个人信息数据
     */
    SaveOrUpdateResumeRequest personalRequest = new SaveOrUpdateResumeRequest();

    private UserOssUtils ossUtils;
//    private String headImageUrl;


    /**
     * 学历数据
     */
    List<JobCommonBean.ItemsEntity> JobCommonList;

    List<JobCommonBean.ItemsEntity> nationList;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, MyResumeAct.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.act_my_resume);
        ButterKnife.bind(this);
        initTitle("我的简历", "保存", saveListener);
        initVeiw();
        initData();
        WorkExperienceFragment.replaceFragment(this, R.id.frag_work_experience);
        ossUtils = new UserOssUtils(this, null);
        ossUtils.initOssData();
//        headImageUrl = UserOssUtils.uploadUrl + CommonValue.headImage + AppSession.getInstance().getUserId() + ".png";

    }

    private void initData() {
        getResumeInfo();
        // 获取学历数据
        getEducationList("es.base.dictionary.EduType", "education");
        // 获取民族数据
        getEducationList("es.base.dictionary.Nation", "nation");
    }

    private View.OnClickListener saveListener = new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            personalRequest.userId = AppSession.getInstance().getUserId();
            String name = etName.getText().toString().trim();
            if (TextUtil.isNotNull(name)) {
                personalRequest.name = name;
            }
            String idCard = etIdcard.getText().toString().trim();
            if (!TextUtil.isIDCard(idCard)) {
                MessageTools.showToast(oThis, "请输入正确的身份证号码");
                return;
            } else {
                personalRequest.idCard = idCard;
            }
            String residentialAddress = etResidentialAddress.getText().toString().trim();
            if (TextUtil.isNotNull(residentialAddress)) {
                personalRequest.residentialAddress = residentialAddress;
            }
            personalRequest.workYears = etWorkAge.getText().toString().trim();
            HttpClient.post(personalRequest, new HttpClient.onSuccessListener() {
                @Override
                public void onSuccess(BaseResponse response) {
                    MessageTools.showToast(oThis, "保存成功");
                    getCheck();

                }
            }, new HttpClient.onFailListener() {
                @Override
                public void onFail(int code, String msg) {
                    MessageTools.showToast(oThis, msg);
                }
            });

        }
    };

    /**
     * 是否完善简历
     */
    private void getCheck() {
        CheckResumeRequest request = new CheckResumeRequest();
        request.userId = AppSession.getInstance().getUserId();
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                CheckResumeResponse response1 = (CheckResumeResponse) response;
                if (response1.status.equals("0")) {
                    AppSession.getInstance().setResumePerfect(false);
                } else if (response1.status.equals("1")) {
                    AppSession.getInstance().setResumePerfect(true);
                } else {
                    AppSession.getInstance().setResumePerfect(false);
                }


            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(oThis, msg);
            }
        });
    }

    private void initVeiw() {
        etIdcard.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//                Log.d("beforeTextChanged.............charSequence = " + charSequence + "----i=" + i + "-----i1=" + i1 + "-----i2=" + i2);
            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
//                Log.d("onTextChanged...........charSequence = " + charSequence + "----i=" + i + "-----i1=" + i1 + "-----i2=" + i2);
            }

            @Override
            public void afterTextChanged(Editable editable) {
                String text = editable.toString();
                Logs.d(tag, "etIdcard  的 afterTextChanged = " + text);
                etIdcard.setSelection(text.length());
                if (editable.length() == 17) {
                    char lastChar = StringUtil.getLastIDCardX(text);
                    if (lastChar == 'x') {
                        etIdcard.setText(text + lastChar);
                    }
                }
            }
        });

        etIdcard.setOnKeyListener(new View.OnKeyListener() {
            @Override
            public boolean onKey(View view, int keyCode, KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_DEL) {

                    int index = etIdcard.getSelectionStart();
                    Editable editable = etIdcard.getText();
                    if (index == 0) {
                        return true;
                    }
                    editable.delete(index - 1, index);
                    String str = editable.toString();
                    if (str.contains("x")) {
                        str = str.substring(0, str.length() - 1);

                    }

                    etIdcard.setText(str);
                }
                return true;
            }
        });
    }

    /**
     * 获取简历信息
     */
    private void getResumeInfo() {
        GetResumeInfoRequest request = new GetResumeInfoRequest();
        request.userId = AppSession.getInstance().getUserId();
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                ResumeInfoResponse resumeInfoResponse = (ResumeInfoResponse) response;
                updateMessage(resumeInfoResponse);

            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
                MessageTools.showToast(oThis, msg);
            }
        });
    }

    /**
     * 获取学历或者薪资数据
     *
     * @param dicId 字典
     * @param key   判断学历还是薪资
     */
    private void getEducationList(String dicId, final String key) {
        final EducationRequest request = new EducationRequest();
        request.dicId = dicId;
        request.parentKey = "";
        request.sliceType = "3";
        request.query = "";
        request.start = 0;
        request.limit = 0;
        HttpClient.post(request, new HttpClient.onSuccessListener() {
            @Override
            public void onSuccess(BaseResponse response) {
                handleData(response, key);
//                JobCommonBean bean = (JobCommonBean) response;
//                JobCommonList = bean.items;
            }
        }, new HttpClient.onFailListener() {
            @Override
            public void onFail(int code, String msg) {
            }
        });
    }

    /**
     * 学历或薪资数据处理
     */
    private void handleData(BaseResponse response, String key) {
        JobCommonBean bean = (JobCommonBean) response;
        if (bean != null && bean.items != null && !bean.items.isEmpty()) {
            if (key.equals("education")) {
                JobCommonList = bean.items;
            } else if (key.equals("nation")) {
                nationList = bean.items;
            }
        }
    }

    private void updateMessage(ResumeInfoResponse response) {
        if (TextUtil.isNotNull(response.name)) {
            etName.setText(response.name);
        }
        if (TextUtil.isNotNull(response.sexText)) {
            tvSex.setText(response.sexText);
            personalRequest.sex = response.sex;
        }
        if (TextUtil.isNotNull(response.eduText)) {
            tvEdu.setText(response.eduText);
            personalRequest.edu = response.edu + "";
        }
        if (TextUtil.isNotNull(response.idCard)) {
            etIdcard.setText(response.idCard);
        }

        if (TextUtil.isNotNull(response.nationalText)) {
            tvNational.setText(response.nationalText);
            personalRequest.national = response.national + "";
        }
        if (TextUtil.isNotNull(response.maritalText)) {
            tvMarital.setText(response.maritalText);
            personalRequest.marital = response.marital;
        }
        if (TextUtil.isNotNull(response.censusRegister) && !response.censusRegister.equals("0")) {
            tvCensusRegister.setText(response.censusRegister);
            personalRequest.censusRegister = response.censusRegister;
        }
        if (TextUtil.isNotNull(response.residentialAddress)) {
            etResidentialAddress.setText(response.residentialAddress);
        }

        if (StringUtil.isNotEmpty(response.age) && !response.age.equals("0")) {
            personalRequest.age = response.age;
        }

        if (response.workYears != 0) {
            etWorkAge.setText(response.workYears + "");
        }

        personalRequest.headImage = response.headImage;

        Picasso.with(oThis).load(response.headImage + "").error(R.mipmap.personal_default).into(imgPerson);

    }

    @OnClick({R.id.ly_img, R.id.img_person, R.id.ly_name, R.id.ly_edu, R.id.ly_sex, R.id.ly_national, R.id.ly_marital, R.id.ly_censusRegister})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ly_img:
            case R.id.img_person:
                openCamera();
                break;
            case R.id.ly_sex:
                selectSex();
                break;
            case R.id.ly_edu:
                selectJobCommon();
                break;
            case R.id.ly_national:
                selectNational();
                break;
            case R.id.ly_marital:
                selectMarital();
                break;
            case R.id.ly_censusRegister:
                //户籍地址
                cityClick();
                break;
        }
    }


    /**
     * 省市区
     */
    private void cityClick() {
        lyCensusRegister.setClickable(false);
        mHandler.sendEmptyMessageDelayed(1, 3 * 1000);
        new CityDialog(this).builder().setPositiveButton("确定", new OnSelectCityImpl() {
            @Override
            public void selectCity(String address, String provinceCode, String cityCode, String areaCode) {
                tvCensusRegister.setText(address);
                personalRequest.censusRegister = address;
                personalRequest.province = provinceCode;
                personalRequest.city = cityCode;
                personalRequest.area = areaCode;
            }
        }).setNegativeButton("取消").show();
    }

    /**
     * 拍照弹出框
     */
    private void openCamera() {
        ArrayList<String> list = new ArrayList<>();
        list.add("相册");
        list.add("拍照");

        MessageTools.showOneChoiceDialog(oThis, "请选择", list, new OneChoiceImpl() {
            @Override
            public void oneChoiceConfig(String text, int position) {
                switch (position) {
                    case 0:
                        // 从相册选取
                        ImageUtils.choicePicture(oThis);

                        break;
                    case 1:
                        // 拍照
                        // 判断存储卡是否可以用，可用进行存储
                        if (ImageUtils.hasSdcard()) {
                            ImageUtils.takePicture(oThis);
                        }
                        break;
                }
            }
        });

    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == CommonValue.RESULT_REQUEST_CODE) {
            //图片截取
            if (data != null) {
                setPersonImage(data);
            } else {
                return;
//                setPersonImage(data, tempFile.getPath());
            }
            return;
        }
        if (resultCode == RESULT_OK) {
            if (requestCode == CommonValue.REQUEST_PICTURE) {
                // 相册
                Uri uri = data.getData();
                ImageUtils.startPhotoZoom(oThis, uri);
            } else if (requestCode == CommonValue.REQUEST_CODE_BASE) {
                if (data != null && data.getData() != null) {
                    // 相机 并且获取到arg2
                    Uri uri = data.getData();
                    ImageUtils.startPhotoZoom(oThis, uri);
                } else {
                    // 相机，获取不到intent数据
                    Uri uri = Uri.parse(CommonValue.openCameraUri);
                    ImageUtils.startPhotoZoom(oThis, uri);
                }
            }
        }

    }

    private void setPersonImage(Intent data) {
        Bitmap bitmap;
        if (data != null) {
            Bundle extras = data.getExtras();
            bitmap = extras.getParcelable("data");
        } else {
            bitmap = null;
        }
        if (bitmap == null) {
            MessageTools.showToast(oThis, "获取图片失败");
            return;
        }
        File uploadFile = new File(FileUtils.getAppPath(), AppSession.getInstance().getUserId() + ".png");
        final String albumPath = uploadFile.getPath();
        FileUtils.compressAndSaveBitmapToFile(bitmap, albumPath, 100);

        upLoadImg(albumPath);


    }

    /**
     * 上传图片
     * 命名
     */
    private void upLoadImg(final String filePath) {
        showMyDialog("正在上传图片");

        String url = CommonValue.headImage + AppSession.getInstance().getUserId() + ".png";
        ossUtils.asyncTaskUpload(url, filePath, getPutCallback(imgPerson, filePath, UserOssUtils.uploadUrl + url));
    }


    // 普通上传回调
    public UICallback<PutObjectRequest, PutObjectResult> getPutCallback(final ImageView view, final String imageName, final String url) {

        return new UICallback<PutObjectRequest, PutObjectResult>(ossUtils.UIDispatcher) {

            @Override
            public void onSuccess(PutObjectRequest request, PutObjectResult result) {

                Logs.d(tag, "UploadSuccess");

                addCallback(new Runnable() {
                    @Override
                    public void run() {
                        File file = new File(imageName);
                        Picasso.with(oThis)
                                .load(file)
                                .memoryPolicy(MemoryPolicy.NO_CACHE)
                                .networkPolicy(NetworkPolicy.NO_CACHE)
                                .into(imgPerson);
                        personalRequest.headImage = url;
                        mHandler.sendEmptyMessage(CommonValue.MSG_LOAD_SUCCES);
//                                upLoadHeadImage(imageName, url);

                    }
                }, null);

                super.onSuccess(request, result);
            }


            @Override
            public void onFailure(PutObjectRequest request, ClientException clientExcepion,
                                  ServiceException serviceException) {

                String info = "";
                // 请求异常
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    info = clientExcepion.toString();
                }
                if (serviceException != null) {
                    // 服务异常
                    Logs.e("ErrorCode", serviceException.getErrorCode());
                    Logs.e("RequestId", serviceException.getRequestId());
                    Logs.e("HostId", serviceException.getHostId());
                    Logs.e("RawMessage", serviceException.getRawMessage());
                    info = serviceException.toString();
                }
                final String outputinfo = new String(info);

                mHandler.sendEmptyMessage(CommonValue.MSG_LOAD_ERROR);
                ossUtils.ossService.stopPutLoad();
            }
        };
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case CommonValue.MSG_LOAD_SUCCES:
                    //图片上传成功
                    closeDialog();
                    break;
                case CommonValue.MSG_LOAD_ERROR:
                    closeDialog();
                    MessageTools.showToast(oThis, "图片上传失败！");
                    break;

                case 1:
                    lyCensusRegister.setClickable(true);
                    break;
            }
        }
    };

    /**
     * 选择民族
     */
    private void selectNational() {
        if (nationList == null || nationList.size() < 1) {
            // 获取民族数据
            MessageTools.showToast(oThis, "正在加载民族数据");
            getEducationList("es.base.dictionary.Nation", "nation");
            return;
        }
        DialogTools.showOneChoiceDialog(this, "请选择民族", nationList, new OneChoiceImpl() {
            @Override
            public void oneChoiceConfig(String text, int position) {
                tvNational.setText(text);
                personalRequest.national = nationList.get(position).key;
            }
        });

    }

    /**
     * 选择学历
     * JobCommonList
     */
    private void selectJobCommon() {
        String[] types;
        if (JobCommonList == null || JobCommonList.size() < 1) {
            types = getResources().getStringArray(R.array.marital);
        } else {
            int size = JobCommonList.size();
            types = new String[size];
            for (int i = 0; i < size; i++) {
                types[i] = JobCommonList.get(i).text;
            }
        }
        MessageTools.showOneChoiceDialog(this, "请选择学历", types, new OneChoiceImpl() {
            @Override
            public void oneChoiceConfig(String text, int position) {
                tvEdu.setText(text);
                if (JobCommonList == null || JobCommonList.size() < 1) {
                    personalRequest.edu = position + "";
                } else {
                    personalRequest.edu = JobCommonList.get(position).key;
                }
            }
        });
    }


    /**
     * 是否已婚
     */
    private void selectMarital() {
        String[] types = getResources().getStringArray(R.array.marital);
        MessageTools.showOneChoiceDialog(this, "是否结婚", types, new OneChoiceImpl() {
            @Override
            public void oneChoiceConfig(String text, int position) {
                tvMarital.setText(text);
                personalRequest.marital = position;
            }
        });
    }


    /**
     * 选择性别
     */
    private void selectSex() {
        String[] types = getResources().getStringArray(R.array.sex);
        MessageTools.showOneChoiceDialog(this, "请选择性别", types, new OneChoiceImpl() {
            @Override
            public void oneChoiceConfig(String text, int position) {
                tvSex.setText(text);
                personalRequest.sex = (position + 1);
            }
        });
    }
}